from ft_table import FtTable, ft
from google.appengine.api import memcache
import logging


#keep all the list functions

_all = {}


def get(key):
    data = memcache.get(key)
    if data is not None:
        return data
    else:
        fn = _all.get(key)
        if fn:
            pass
        else:
            logging.info('%s is missed by memcache, try to request the data' % key)
            _init()
            return memcache.get(key)
        data = _all[key](key)
        memcache.set(key, data, 300)
        return data
def update(key):
    data = _all[key]()
    memcache.set(key, data, 300)
    return data

def set(key, value):
    memcache.set(key, value, 300)
    

        
def get_dlz_schema(key):
    '''
    The mapping between fusion tables and iform tables
    '''
    logging.info('requesting dlz_table_schema table')
    table_id = ft(None, None).getTableId('dlz_table_schema')
    f = FtTable(None, None, table_id)
    sql = 'select * from %s' % f.tableid
    results = f.SqlQuery(sql)
    schema = {}
    for row in results:
        schema['dlz_table_name'] = row
   
        _all[row['dlz_table_name']] = get_dlz_schema
        set(row['dlz_table_name'],  row)
    return memcache.get(key)

def get_dlz_config(key):
    logging.info('requesting dlz_config table')
    table_id = get('DLZ_CONFIG')['ft_table_id']
    f = FtTable(None, None, table_id)
    for row in f.all():
        _all[row['dlz_parameter']] = get_dlz_config
        set(row['dlz_parameter'], row['value'])
    return memcache.get(key)
    



def get_dlz_compaction_schema():
    f = FtTable(None, None, get('DLZ_COMPACTION_SCHEMA')['ft_table_id'])
    results = f.all()
    row1 = []
    row2 = []
    for r in results:
        row1.append(r['compaction_field'])
        row2.append(r['Label'])
    headers = [row1, row2]
    return headers
    
    
_all = {
        'DLZ_TABLE_SCHEMA': get_dlz_schema
        }


def _init():
    """
    pull all the values into memcache
    """
    get_dlz_schema('')
    get_dlz_config('')

